#include "../../base/Utils.h"
#include "../../net/TcpServer.h"
#include "../../logging/Logging.h"
#include "../../net/TcpClient.h"
#include "../../thread/Atomic.h"
#include "../../mutex/MutexLock.h"

#include <queue>
#include <utility>

#include <stdio.h>
#include <unistd.h>
#include <string>

using namespace yhaida;
using std::string;
class MultiplexServer : yhaida::Utils::nocapyable
{
public:
    MultiplexServer(EventLoop *loop,
                    const InetAddress &listenAddr,
                    const InetAddress &serverAddr,
                    int numThreads);
    ~MultiplexServer() = default;

    void start();

private:
    void onClientConnection(const TcpConnectionPtr &conn);
    void onClientMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp);

    void onBackendConnection(const TcpConnectionPtr &conn);
    void onBackendMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp);
    void sendToClient(Buffer *buffer);

    void doCommand(const string& cmd);
    void printStatistics();

private:
    /*
     * 封包及发送
     */
    void sendBackendPacket(int id, Buffer *buffer);
    void sendBackendString(int id, const string &msg);
    void sendBackendBuffer(int id, Buffer *buffer);

private:
    static const int kMaxConns = 10; // 65535
    static const size_t kMaxPacketLen = 255;
    static const size_t kHeaderLen = 3;

private:
    TcpServer _server;
    TcpClient _backendClient;
    TcpConnectionPtr _backendConn;//共享资源
    int _numTheads;

    AtomicInt64 _transferred;
    AtomicInt64 _receivedMessages;

    int64_t _oldCounter;
    Timestamp _startTime;

    MutexLock _mutex;

    std::map<int, TcpConnectionPtr> _clientConns;
    std::queue<int> _availIds;//共享资源
};